package chapter16.event;

import javax.swing.*;
import java.awt.*;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;

/**
 * @Auther: Tx
 * @Date: 2022/5/28 19:20
 * 演示小球通过键盘控制键盘上下左右的移动
 */
public class BollMove extends JFrame{
    MyPanel mp = null;
    public static void main(String[] args) {
        new BollMove();
    }
    public BollMove(){
        mp = new MyPanel();
        this.add(mp);
        this.setSize(400,300);
//       窗口JFrame对象可以监听键盘事件，即可以监听到面板发生的键盘事件
        this.addKeyListener(mp);
        this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        this.setVisible(true);
    }
}
//KeyListener ，可以监听键盘事件
class MyPanel extends JPanel implements KeyListener {
    int x = 10;
    int y = 10;
    @Override
    public void paint(Graphics g) {
        super.paint(g);
        g.fillOval(x,y,20,20);
    }
//    有字符输出时，该方法就会触发
    @Override
    public void keyTyped(KeyEvent e) {

    }
//当某个键按下时，该方法会触发
    @Override
    public void keyPressed(KeyEvent e) {
//        根据用户按下的不同键，来处理小球的移动
        if (e.getKeyCode() == KeyEvent.VK_DOWN){
            y++;
            this.repaint();
        }else if (e.getKeyCode() == KeyEvent.VK_UP){
            y--;
            this.repaint();
        }else if(e.getKeyCode() == KeyEvent.VK_LEFT){
            x--;
            this.repaint();repaint();
        }else if(e.getKeyCode() == KeyEvent.VK_RIGHT){
            x++;
            this.repaint();
        }
    }
//当某个键释放时，该方法触发
    @Override
    public void keyReleased(KeyEvent e) {

    }
}
